<template>
  <el-radio-group
    v-model="currValue"
    v-bind="options"
  >
    <el-radio
      v-for="item in (dataList && dataList.length > 0 ? dataList : [{key: '', value: ''}])"
      :key="item.key"
      :value="item.key"
    >{{item.value}}</el-radio>
  </el-radio-group>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import visual from "@/visual/js/visual";
import { getDictionary } from '@/utils/system';

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const currValue = ref('');
const currDictCode = ref('');
const dataList = ref([]);

const init = () => {
  const compStyle = props.compStyle || {};
  currValue.value = compStyle['default'] || '';

  if (compStyle['dataSource'] === 'enum') {
    const optionList = [];
    (compStyle['enumValue'] || '').split(',').forEach(item => {
      optionList.push({key: item, value: item});
    });
    dataList.value = optionList;
  } else if (compStyle['dataSource'] === 'dict') {
    currDictCode.value = compStyle['dictCode'] || '';
    loadDictionary(currDictCode.value);
  }

  if (!props.compData?.dataSourceType) {
    loadValue();
  }
};

const options = computed(() => {
  const compStyle = props.compStyle || {};
  const data = {};
  visual.addIfNotNull(data, compStyle, 'size');
  visual.addIfNotNull(data, compStyle, 'placeholder');
  visual.addIfNotNull(data, compStyle, 'required');
  visual.addIfNotNull(data, compStyle, 'disabled');
  return data;
});

const loadDictionary = (dictCode) => {
  if (!dictCode) {
    dataList.value = [];
  }

  getDictionary(dictCode).then(res => {
    dataList.value = res;
  });
}

const loadValue = async() => {
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  currValue.value = dataList.length > 0 && dataList[0]['内容'] || '';
};

watch(() => props.compStyle, () => {
  init();
}, {deep: true});

watch(() => props.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  init();
  loadValue();
});
</script>